package net.lwf.pdf.util;

import net.lwf.pdf.IPdfConstant;

import com.itextpdf.text.Document;
import com.itextpdf.text.Element;
import com.itextpdf.text.ExceptionConverter;
import com.itextpdf.text.Image;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.Phrase;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfPageEventHelper;
import com.itextpdf.text.pdf.PdfWriter;

public class LwfHeaderFooter  extends PdfPageEventHelper {
	
	private String headerImage;
	
	public LwfHeaderFooter(String _headerimage) {
		this.headerImage = _headerimage;
	}

	/**
	 * This method demonstrates displaying image in the header and simple text in the
	 * footer using tables.
	 *  
	 * @param writer
	 * @param document
	 */
	public void onEndPage(PdfWriter writer, Document document) {
		String namedate = IPdfConstant.PORTRAIT_NAMEDATE;
		Rectangle paper = document.getPageSize();
		try {

			//Always set the image with absolute path (not the relative path)
			Image jpg = Image.getInstance(this.headerImage);

			jpg.scaleToFit(200, 50);

			Rectangle page = document.getPageSize();

			PdfPTable head = new PdfPTable(3);
			
			PdfPCell cell = new PdfPCell(jpg);
			cell.setBorder(0);
			head.addCell(cell);
			if(paper.getWidth() != PageSize.A4.getWidth()) {
				namedate = IPdfConstant.LANDSCAPE_NAMEDATE;
			}
			cell = new PdfPCell(new Phrase(namedate));
			cell.setColspan(2);
			cell.setBorder(0);
			cell.setVerticalAlignment(Element.ALIGN_BOTTOM);
			head.addCell(cell);
				
			head.setTotalWidth(page.getWidth() - document.leftMargin() - document.rightMargin());
			head.writeSelectedRows(0, -1, document.leftMargin(), page.getHeight() - document.topMargin() + head.getTotalHeight(), writer.getDirectContent());
	         
	         
			//Footer	
			PdfPTable foot = new PdfPTable(1);
			PdfPCell footercell = new PdfPCell(new Phrase(IPdfConstant.FOOTER_PHRASE));
			footercell.setHorizontalAlignment(Element.ALIGN_CENTER);
			footercell.setBorder(0);
			foot.addCell(footercell);
			
			foot.setTotalWidth(page.getWidth() - document.leftMargin() - document.rightMargin());
			foot.writeSelectedRows(0, -1, document.leftMargin(), document.bottomMargin(), writer.getDirectContent());

		}

		catch (Exception e) {
			throw new ExceptionConverter(e);
		}
	}

}
